from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from django.shortcuts import Http404
from crm.libs import forms
from crm import models
from django.db import IntegrityError
from django.urls import reverse
from django.http import FileResponse
import string
import random
from django.core.cache import cache
from crm_demo import settings
import os
import json
from django.contrib.auth.decorators import login_required
from common_libs.permissions import permission

# Create your views here.

def index(request):
    '''销售视图首页'''
    return render(request, 'index.html')

def sales(request):
    '''销售视图首页'''
    return render(request, 'index.html')


def customer_list(request):
    '''客户库'''
    return render(request, 'sales/customers.html')



@login_required
@permission.check_permission
def enrollment(request, customer_id):
    '''报名页面'''
    customer_obj = models.Customer.objects.get(id=customer_id)
    msg = ''
    random_str = ''.join(random.sample(string.ascii_lowercase+string.digits,8))
    if request.method == 'GET':
        form_obj = forms.EnrollmentForm()
    elif request.method == 'POST':
        form_obj = forms.EnrollmentForm(request.POST)
        if form_obj.is_valid():
            # 防止重复数据
            try:
                form_obj.cleaned_data['customer'] = customer_obj    # 添加customer信息
                enrollment_obj = models.Enrollment.objects.create(**form_obj.cleaned_data)
            except IntegrityError:
                form_obj.add_error('__all__','已存在相同的报名信息')
                enrollment_obj = models.Enrollment.objects.get(customer_id=customer_id,
                                                               enrolled_class_id=form_obj.cleaned_data['enrolled_class'])

                if enrollment_obj.contract_agreed == True:
                    # 进入审核流程
                    url = reverse('contract_review',kwargs={'enrollment_id':enrollment_obj.id})
                    return redirect(url)
            registriation_url = reverse('registriation', kwargs={'enrollment_id': enrollment_obj.id,'random_str':random_str})
            msg = '请将以下链接发给客户: {schema}://{host}{registriation_url}'.format(
                schema=request.META['wsgi.url_scheme'],
                host=request.get_host(),
                registriation_url=registriation_url,
            )

            cache.set(enrollment_obj.id, random_str,600)    # 报名链接生效时间


    res_dict = {'form_obj': form_obj,
                'customer_obj': customer_obj,
                'msg':msg}
    return render(request, 'sales/enrollment.html', res_dict)


def stu_registriation(request, enrollment_id, random_str):
    '''学员进行报名确认页'''
    enrollment_obj = models.Enrollment.objects.get(id=enrollment_id)
    customer_obj = enrollment_obj.customer
    is_agreed = False
    if enrollment_obj.contract_agreed == True:
        is_agreed = True
    if request.method == 'GET':
        if not random_str == cache.get(enrollment_obj.id):
            return  HttpResponse('该链接已失效')
        form_obj = forms.registriationForm(instance=customer_obj)
    elif request.method == 'POST':
        if request.is_ajax():
            data_dir = os.path.join(settings.IDCARD_UPLOAD_DIR,enrollment_id)
            if not os.path.exists(data_dir):
                os.makedirs(data_dir,  exist_ok=True)
            for k,file_obj in request.FILES.items():
                f = open(os.path.join(data_dir,file_obj.name),'wb')
                for chunk in file_obj.chunks():
                    f.write(chunk)
                f.close()
            return HttpResponse('ok')
        
        form_obj = forms.registriationForm(request.POST,instance=customer_obj)
        if form_obj.is_valid():
            form_obj.save()
            enrollment_obj.contract_agreed = True
            enrollment_obj.save()
            is_agreed = True
        else:
            print(form_obj.errors)

    res_dict = {'form_obj': form_obj,
                'enrollment_obj':enrollment_obj,
                'is_agreed':is_agreed}
    return render(request, 'sales/stu_registriation.html',res_dict)



@login_required
@permission.check_permission
def contract_review(request, enrollment_id):
    '''审核报名信息'''
    if request.method == 'GET':
        enrollment_obj = models.Enrollment.objects.get(id=enrollment_id)
        if not enrollment_obj.contract_agreed :
            url = reverse('enrollment', kwargs={'customer_id': enrollment_obj.customer_id})
            return redirect(url)
        file_dir = os.path.join(settings.IDCARD_UPLOAD_DIR,enrollment_id)
        photo_list = os.listdir(file_dir)

        res_dict = {'customer': enrollment_obj.customer,
                    'enrollment': enrollment_obj,
                    'photo_list': photo_list}
        return render(request,'sales/contract_review.html',res_dict)


@login_required
@permission.check_permission
def id_photo(request,enrollment_id,file_name):
    '''获取证件照'''
    file_path = os.path.join(settings.IDCARD_UPLOAD_DIR, enrollment_id, file_name)
    if not os.path.exists(file_path):
        raise Http404
    else:
        file = open(file_path, 'rb')
        data = file.read()
        file.close()
        return HttpResponse(data,content_type="image/png")


@login_required
@permission.check_permission
def enrollment_objection(request,enrollment_id):
    '''驳回合同'''
    enrollment_obj = models.Enrollment.objects.get(id=enrollment_id)
    enrollment_obj.contract_agreed = False
    enrollment_obj.save()
    url = reverse('enrollment', kwargs={'customer_id': enrollment_obj.customer_id})
    return redirect(url)



@login_required
@permission.check_permission
def payment(request, enrollment_id):
    '''添加缴费记录'''
    error_msg = ''
    enrollment_obj = models.Enrollment.objects.get(id=enrollment_id)
    if request.method == 'GET':
        if not enrollment_obj.contract_agreed :
            # 判断学生是否提交审核
            url = reverse('enrollment', kwargs={'customer_id': enrollment_obj.customer_id})
            return redirect(url)
    elif request.method == 'POST':
        payment_amount = request.POST.get('payment_amount')
        if payment_amount and payment_amount.isdigit():
            if int(payment_amount)>= 500:
                models.Payment.objects.create(customer=enrollment_obj.customer,
                                              course=enrollment_obj.enrolled_class.course,
                                              amount=int(payment_amount),
                                              consultant=enrollment_obj.consultant,
                                              )
                enrollment_obj.contract_approved = True
                enrollment_obj.customer.status=0
                enrollment_obj.customer.save()
                enrollment_obj.save()

                url = reverse('table_detail',kwargs={'app_name':'crm','table_name':'customer'})
                return redirect(url)

        error_msg='缴费金额不能少于500'

    res_dict = {'enrollment': enrollment_obj, 'error_msg': error_msg}
    return render(request, 'sales/payment.html', res_dict)



def class_list(request):
    '''班级管理'''
    return render(request,'sales/class_list.html')


@login_required
@permission.check_permission
def download_homework(request,class_id,course_id,studyrecord_id):
    '''下载作业'''
    data_dir = os.path.join(settings.HOMEWORK_UPLOAD_DIR, class_id, course_id, studyrecord_id)
    if os.path.exists(data_dir):
        if len(os.listdir(data_dir)) > 0:
            file_name = os.listdir(data_dir)[0]
            file_path = os.path.join(data_dir,file_name)
            file = open(file_path,'rb')
            res = FileResponse(file)
            res['Content-Type'] = 'application/octet-stream'
            res['Content-Disposition'] = 'attachment;filename=%s'%file_name
            return res
    return HttpResponse('没有该文件')


def file_list(request,enrollment_id):
    '''获取上传文件的列表'''
    file_dir = os.path.join(settings.IDCARD_UPLOAD_DIR, enrollment_id)
    if os.path.exists(file_dir):
        file_list = os.listdir(file_dir)
    else:
        file_list = []
    return HttpResponse(json.dumps(file_list))


def file_delete(request, enrollment_id,file_name):
    '''删除指定的文件'''
    file_path = os.path.join(settings.IDCARD_UPLOAD_DIR, enrollment_id, file_name)
    print(file_path)
    if os.path.exists(file_path):
        os.remove(file_path)
        return HttpResponse('ok')
    else:
        return HttpResponse('wrong')


